package com.haojii.jdo.basic;
import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.haojii.jdo.utils.PMF;

@SuppressWarnings("serial")
public class UserUnEncodedStringKeyTestServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		System.out.println("1.0 Create and persist UserUnEncodedString with @PrimaryKey: String name");
		UserUnEncodedString UserUnEncodedString = new UserUnEncodedString("key_name1",UserUnEncodedString.class.getSimpleName());
		pm.makePersistent(UserUnEncodedString);
		
		System.out.println("1.1 Query UserUnEncodedString with getObjectById");
	    UserUnEncodedString tmpUserUnEncodedString = null;
	    String key = UserUnEncodedString.getName();
	    tmpUserUnEncodedString = pm.getObjectById(UserUnEncodedString.class, key);
	    System.out.println("UserUnEncodedString==tmpUserUnEncodedString?"+(UserUnEncodedString==tmpUserUnEncodedString));
	    
	    System.out.println("1.2 Query UserUnEncodedString with key_name1");
	    tmpUserUnEncodedString = null;
	    Query query = pm.newQuery(UserUnEncodedString.class); 
	    query.setFilter("name == nameParam"); 
	    query.setOrdering("date desc"); 
	    query.declareParameters("String nameParam");
	    try { 
	        List<UserUnEncodedString> results = (List<UserUnEncodedString>) query.execute("key_name1"); 
	        System.out.println("All UserUnEncodedString size:"+results.size());
	        if (results.iterator().hasNext()) { 
	            for (UserUnEncodedString e : results) { 
	            	tmpUserUnEncodedString = e;
	                System.out.println(" "+e);
	            } 
	        } else { 
	        	System.out.println("1.2 Query get empty result");
	        } 
	    } finally { 
	        query.closeAll(); 
	    }
	    
	    if (tmpUserUnEncodedString != null)
	    {
	    	System.out.println("1.3 Update the searched result[0] UserUnEncodedString with key_name1->KEY_NAME!");
	    	System.out.println("UserUnEncodedString==tmpUserUnEncodedString?"+(UserUnEncodedString==tmpUserUnEncodedString));
	    	tmpUserUnEncodedString.setName("KEY_NAME!");
	    	pm.makePersistent(tmpUserUnEncodedString);
	    }
	    
	    System.out.println("1.4 Delete UserUnEncodedString with key_name1");
	    System.out.println(" ->"+UserUnEncodedString);
	    pm.deletePersistent(UserUnEncodedString);

	    
	    query = pm.newQuery(UserUnEncodedString.class); 
	    System.out.println("All UserUnEncodedString size:"+((List<UserUnEncodedString>) query.execute()).size());
		resp.getWriter().println("Hello, world");
	}
}
